package com.pesking.core.sqlparser.processor;

import java.util.Arrays;
import java.util.List;

import com.pesking.core.exception.SystemException;
import com.pesking.core.globalid.GlobalIdManage;
import com.pesking.core.parameter.Parameter;
import com.pesking.core.sqlparser.parameter.SqlParameter;
import com.pesking.core.sqlparser.parameter.SqlParameterProcessor;
import com.pesking.core.sysparam.SystemParameterManage;
import com.pesking.core.util.LogUtils;
import com.pesking.core.util.StringUtils;

/**
 * 流水号生成SQL参数处理类
 * @author ChenYunpei
 * @since 2014-12-16
 */
public class SerialNumberSqlParameterHandler extends SqlParameterProcessor {
	@Override
	public String getTitle() {
		return "流水号参数";
	}

	@Override
	public String getDescription() {
		return this.getTitle() + " 使用方法：[SN:请求参数名：关键字段名1@关键字段名1@关键字段名1:顺序号位数],首先借助关键字段名从请求中取动态值，如果取不到以关键字段名作为值";
	}

	@Override
	public List<String> getSqlParameterType() {
		return Arrays.asList(new String []{"SN","SERIAL_NUMBER"});
	}

	@Override
	public void handle(StringBuilder sbSQL, Parameter parameter, List<SqlParameter> processors,SqlParameter sqlParameter) {
		String name = sqlParameter.getName();
		String field = sqlParameter.getValue();
		String value = sqlParameter.getField(1);
		if (StringUtils.isBlank(value)){
			value = "6";
		}
		if (StringUtils.isBlank(field)){
			throw new SystemException("参数设置错误,关键字段名不能为空，使用方法：[SN:请求参数名：关键字段名1@关键字段名1@关键字段名1:顺序号位数],首先借助关键字段名从请求中取动态值，如果取不到以关键字段名作为值");
		}
		int count = Integer.parseInt(value);
		String []arr = field.split("@");
		String key = "";
		if (arr != null){
			int len = arr.length;
			for (int i = 0 ; i < len ; i++){
				String v = parameter.getParameter(arr[i]);
				if (v == null) {
					v = SystemParameterManage.getString(arr[i]);
				}
				if (v != null) {
					key += v.trim();
				}
			}
		}
		String uuid = GlobalIdManage.generateFixedLength(key, key, key.length() + count);
		if (!StringUtils.isBlank(name)){
			parameter.setParameter(name, uuid);
		}
		LogUtils.debug( "SN参数:name[" + name + "]value[" + uuid + "]");
		sbSQL.append(uuid);
	}
	
}
